<?php

namespace app\api\controller;

use app\common\exception\BaseException;
use app\common\model\User as UserModel;

class User extends Controller
{
    /**
     * app/web/等手机号登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function app_login()
    {

        $model = new UserModel;
        try {
            $user = $model->app_login($this->request->post());
        } catch (\Exception $e) {
            return $this->renderError($e->getMessage());
        }

        return $this->renderSuccess([
            'user_id' => $user['user_id'],
            'token' => $model->getToken()
        ]);
    }


    //游客登录
    function anonymous_login()
    {
        $model = new UserModel;
        try {
            $user = $model->reg(array_merge(['from' => 'anonymous'], $this->request->post()));
        } catch (BaseException $e) {
            return $this->renderError($e->getMessage());
        }
        return $this->renderSuccess([
            'user_id' => $user['user_id'],
            'token' => $model->getToken()
        ]);
    }

    /*
    *app/web/等手机号注册
    * @return array
    */
    public function app_reg()
    {
        $model = new UserModel;

        try {
            $user = $model->reg($this->request->post());
        } catch (BaseException $e) {
            return $this->renderError($e->getMessage());
        }

        return $this->renderSuccess([
            'user_id' => $user['user_id'],
            'token' => $model->getToken()
        ]);

    }

    /*
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {

        $model = new UserModel;

        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }

    /**
     * 更新用户信息
     * @throws \think\exception\DbException
     */
    public function updateUser()
    {
        $model = new UserModel;
        $user = $model::getUser($this->request->post('token'));
        $data = json_decode(htmlspecialchars($this->request->post('userInfo')), true);
        $res = $model->allowField(true)->save($data, ['user_id' => $user['user_id']]);
        return $this->renderSuccess([
            'res' => $res,
            'oist' => $this->request->post()
        ]);
    }

}
